export type ClassConstructor<T> = {
  new (...args: any[]): T;
};

export class JsonUtil {

  /**
   * let datas = parseJson(ContactEntity, `{"username":"test","company":"盈世", "_emails":"['test@coremail.cn','bwen1@coremail.cn']"}`);
   * @param clz 目标类型
   * @param json  JSON 字符串
   * @returns clz 对象
   */
  static parseJson<T>(clz: ClassConstructor<T>, json: string): T {
    //
    let cls: T = new clz();
    let obj = JSON.parse(json);
    let arr2 = Object.keys(obj);
    arr2.forEach((key: string) => {
      cls[key] = obj[key];
    });
    return cls;
  }

  /**
   *  let datas = parseJsonArray(ContactEntity, `[{"username":"zhangsan","company":"盈世", "_emails":"['zhangsan@coremail.cn','zhangsan@coremail.cn']"}
   * ,{"username":"lisi","company":"盈世", "_emails":"['lisi@coremail.cn','lisi@coremail.cn']"}]`);
   * @param clz 目标类型
   * @param jsonArray 字符串
   * @returns Array<clz> 数组
   */
  static parseJsonArray<T>(clz: ClassConstructor<T>, jsonArray: string): Array<T> {

    let arr = JSON.parse(jsonArray);
    let result = [];
    if (arr && arr.constructor === Array) {
      arr.forEach((value) => {

        let cls: T = new clz();
        let arr2 = Object.keys(value);

        arr2.forEach((key: string) => {
          cls[key] = value[key];
        });

        result.push(cls)
      })
    }
    return result;
  }
}